package com.qqt.csr.order.service.statemachine.condition.impl;

import com.qqt.csr.common.exception.StatusCode;
import com.qqt.csr.common.utils.ServiceAssert;
import com.qqt.csr.order.entity.WorkOrder;
import com.qqt.csr.order.enums.WorkOrderEventEnum;
import com.qqt.csr.order.service.statemachine.condition.ISubCondition;
import com.qqt.csr.order.service.statemachine.context.WorkOrderContext;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

@Component
public class EditedWorkOrderSubCondition implements ISubCondition {
    @Override
    public boolean matches(WorkOrderEventEnum event) {
        return WorkOrderEventEnum.EDITED.equals(event) || WorkOrderEventEnum.EDIT_ALLOCATED.equals(event);
    }

    @Override
    public boolean isSatisfied(WorkOrderContext context) {
        WorkOrder toOrder = context.getToOrder();
        WorkOrder fromOrder = context.getFromOrder();
        if (fromOrder.isAllocated()) {
            ServiceAssert.isTrue(fromOrder.getCreatorId().equals(context.getOperatorId()) || fromOrder.getDesigneeId().equals(context.getOperatorId()), StatusCode.Common.ILLEGAL.getCode(), "无权限操作");
        } else {
            ServiceAssert.isTrue(fromOrder.getCreatorId().equals(context.getOperatorId()), StatusCode.Common.ILLEGAL.getCode(), "无权限操作");
        }

        ServiceAssert.isTrue(fromOrder.isToProcess() || fromOrder.isToClaim(), StatusCode.Common.ILLEGAL.getCode(), "非待领取或处理中的工单无法修改！");
        ServiceAssert.isTrue(fromOrder.isToClaim() || toOrder.getDesigneeId() != null, StatusCode.Common.ILLEGAL.getCode(), "处理中的工单不能将处理人置空！");
        ServiceAssert.isTrue(!toOrder.isTimeOutConfig() || (toOrder.getTimeoutConfig() != null && toOrder.getTimeoutConfig() > 0), StatusCode.Common.ILLEGAL.getCode(), "工单超时时间不能为空！");
        ServiceAssert.isTrue(!toOrder.isBindConversation() || StringUtils.isNotBlank(toOrder.getConversationId()), StatusCode.Common.ILLEGAL.getCode(), "关联的会话id不能为空！");
        return true;
    }
}
